#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
#include "x86.h"
#include "traps.h"
#include "spinlock.h"

// Interrupt descriptor table (shared by all CPUs).
struct gatedesc idt[256];
extern uint vectors[];
struct spinlock tickslock;
uint ticks;

void
tvinit(void)
{
	int i=0;
	for(i = 0; i < 256; i++)
	    SETGATE(idt[i], 0, SEG_KCODE<<3, vectors[i], 0);
	  SETGATE(idt[T_SYSCALL], 1, SEG_KCODE<<3, vectors[T_SYSCALL], DPL_USER);
  
  initlock(&tickslock, "time");
}

void
idtinit(void)
{
  lidt(idt, sizeof(idt));
}

void
trap(struct trapframe *tf)
{
  if(tf->trapno == T_SYSCALL){
    proc->tf = tf;
    syscall();
    return;
  }

  switch(tf->trapno){
  case T_IRQ0 + IRQ_TIMER:
    if(cpu->id == 0){
      acquire(&tickslock);
      ticks++;
      release(&tickslock);
    }
    if(proc){
    	proc->pticks++;
    	if(proc->pticks%20==0){
    		cprintf("cpu=%d,pid=%d,pticks=%d,timer interrupt!\n",
    				cpu->id,proc->pid,proc->pticks);
    	}
    }
    lapiceoi();
    break;
  case T_IRQ0 + IRQ_COM1://IRQ_COM1表示IRQ4（串口设备中断）
    uartintr();
    lapiceoi();
    break;

  case T_IRQ0 + IRQ_KBD:
  	  kbdintr();
      lapiceoi();
      break;
   
  default:
    if(proc == 0 || (tf->cs&3) == 0){
      // 内核空间不触发其他中断，如果有中断，那就表示有问题，panic
      cprintf("unexpected trap %d from cpu %d eip %x (cr2=0x%x)\n",
              tf->trapno, cpu->id, tf->eip, rcr2());
      panic("trap");
    }
    // 在用户空间，可能是用户误操作，打印信息即可
    cprintf("pid %d %s: trap %d err %d on cpu %d "
            "eip 0x%x addr 0x%x--kill proc\n",
            proc->pid, proc->name, tf->trapno, tf->err, cpu->id, tf->eip, 
            rcr2());
  }

  // 当前进程正在运行，且是时钟中断，则进程切换
  if(proc && proc->state == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)
    yield();

}
